package com.kuang.controller;


import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kuang.common.Result;
import com.kuang.exception.ServiceException;
import com.kuang.mapper.UserMapper;
import com.kuang.pojo.User;
import com.kuang.service.impl.UserServiceImpl;
import com.kuang.utils.TokenUtils;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.rmi.ServerException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserServiceImpl userService;

    //查询功能
    @GetMapping("/select")
    public Result selectAllUser(){
        //添加条件构造器
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        //设置排序条件
        wrapper.orderByDesc("id");
        //List<User> users = userMapper.selectAllUser();
        List<User> users = userService.list(wrapper);
        for (User user : users) {
            System.out.println(user);
        }
        return Result.success(users);
    }

    //登陆功能
    @PostMapping("/login")
    public Result login(@RequestBody User user, HttpServletRequest request){
        User user1 = userService.selectUserByUsername(user);

        if (!user.getPassword().equals(user1.getPassword())){
            return Result.error("用户名或密码不正确");
        }
        //将id存入session
        //request.getSession().setAttribute("userId",user1.getId());

        //将含有token的user对象返回给前端
        return Result.success(user1);
    }

    //注册功能
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        //先进行判断，这个用户名有没有重复
        User username = userMapper.selectUserByUsername(user);
        System.out.println("查到了："+username);
        if (username != null){
            throw new ServiceException("用户名已存在");
        }
        int res = userMapper.addUser(user);
        log.info("员工信息:{}",user.toString());
        return Result.success("添加成功");
    }

    //修改用户
    @PutMapping("/update")
    public Result update(@RequestBody User user){
        if(userMapper.updateUser(user)){
            return Result.success();
        }
       return Result.error("上传失败");
    }

    /**
     * 重置密码
     * @param user
     * @return
     */
    @PutMapping("/reset")
    public Result resetPassword(@RequestBody User user){
        System.out.println("user对象："+user);
        boolean res = userService.resetPassword(user);
        if (res){
            return Result.success("重置成功，初始密码为:123");
        }
        return Result.error("无法重置密码");
    }

    /**
     * 通过id删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){
        User currentUser = TokenUtils.getCurrentUser();
        if (currentUser != null && id.equals(currentUser.getId())){
            throw new ServiceException("您不能删除该当前用户");
        }
        userService.removeById(id);
        return Result.success();
    }

    /**
     * 通过id批量删除用户
     * @param ids
     * @return
     */
    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids){
        User currentUser = TokenUtils.getCurrentUser();
        if (currentUser != null && currentUser.getId() != null && ids.contains(currentUser.getId())){
            throw new ServiceException("您不能删除当前用户");
        }
        userService.removeBatchByIds(ids);
        return Result.success();
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam("pageNum") Integer pageNum,
                               @RequestParam("pageSize") Integer pageSize,
                               @RequestParam("name") String name){
        //构造分页查询器
        Page<User> pageInfo = new Page<>(pageNum,pageSize);
        //构造条件查询器
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        //添加一个排序条件
        wrapper.orderByAsc("id");
        //添加模糊查询
        wrapper.like(StringUtils.isNotBlank(name),"name",name);
        //执行查询
        userService.page(pageInfo, wrapper);
        //返回数据
        return Result.success(pageInfo);
    }

    /**
     * 新增用户
     * @param user
     * @return
     */
    @PostMapping("/add")
    public Result addUser(@RequestBody User user){
        userService.save(user);
        return Result.success();
    }

    /**
     * 批量导出
     * @param name
     */
    @GetMapping("/export")
    public void exportData(@RequestParam(required = false) String name,
                           @RequestParam(required = false) String ids,
                           HttpServletResponse response) throws IOException {
        ExcelWriter writer = ExcelUtil.getWriter(true);
        List<User> list = new ArrayList<>();

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();

        //指定用户导出：如果ids不为空(也就是我勾选了复选框)，就执行将传进来的ids字符串转换成数组类型的操作然后导出勾选的用户数据，否则就执行全部导出
        if(StringUtils.isNotBlank(ids)){
            //将字符串按逗号分割成数组
            String[] id = ids.split(",");
            // 使用 Stream API 将字符串数组转换为整数集合
            List<Integer> userId = Arrays.stream(id).map(Integer::valueOf).collect(Collectors.toList());
            wrapper.in(StringUtils.isNotBlank(ids),User::getId,userId);

        }else {
            //全部用户导出：(当name为空的时候执行，也就是说前端没有勾选复选框时，全部导出)
            wrapper.like(StringUtils.isNotBlank(name),User::getName,name);
        }
        list = userService.list(wrapper);
        writer.write(list,true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode("用户信息表","UTF-8")+".xlsx");
        //获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //将excel写入到输出流里，并设置用完流之后就关闭
        writer.flush(outputStream,true);
        //关闭write
        writer.close();
    }

    /**
     * Excel导入
     * @param file  Excel表格要以文件的形式上传
     * @return
     */
    @PostMapping("/import")
    public Result importData(MultipartFile file) throws IOException {
        try {
            //获取inputStream流
            InputStream inputStream  = file.getInputStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream);
            List<User> userList = reader.readAll(User.class);
            userService.saveBatch(userList);
        } catch (Exception e) {
            throw new ServiceException("文件上传失败");
        }
        return Result.success();
    }
}
